<template>
    <div>
        <Row>
            <div style="float:left;margin:5px 5px 5px 5px"  >
                <Button @click="btn_add_site" v-has="'add_site'">新增站点</Button>
            </div>
            <div>
                <div style="width:300px; float:left;">
                    <Form ref="select">
                        <Form-Item  prop="selectContent" >
                            <Input v-model="selectContent" placeholder="输入查询内容" @on-change="btn_select_site" />
                        </Form-Item>
                    </Form> 
                </div>
                <div>
                    <Button type="primary" style="margin-bottom: 5px ;margin-right:5px;margin-left: 5px;"  @click="btn_select_site" >查询</Button>
                </div>
            </div>
        </Row>
        <!-- 列表区域 -->
        <i-table border stripe  :columns="format" :data="show_list" height="720">
            <template slot-scope="{ row, index }" slot="action">
                <Dropdown trigger="click">
                    <a href="javascript:void(0)">
                        <Icon type="ios-create-outline" size="30" />
                    </a>
                    <DropdownMenu slot="list">
                        <DropdownItem><Button type="primary"  @click="btn_edit_site(index)" v-has="'edit_site'">编辑</Button></DropdownItem>
                        <DropdownItem><Button type="error"   @click="del_site(index)" v-has="'delete_site'">删除</Button></DropdownItem>
                    </DropdownMenu>
                </Dropdown>
            </template>
        </i-table >
        <div style="text-align: center;margin-top: 10px;">
            <Page ref="page" :total="total" :page-size="pageSize"  @on-change="changePage" show-total/>
        </div>
        <!-- 新增站点模态框 -->
        <Modal v-model="show_add_site_modal" width="800" draggable>
            <p slot="header" style="color:#f60;text-align:center">
                <span>添加站点</span>
            </p>
            <div >
                <Form ref="site" :model="site" :rules="site_rules" label-position="left"  :label-width="100">
                    <Form-Item label="选择环境" prop="env">
                        <Select v-model="site.env">
                            <Option v-for="env in env_list" :key="env" :value="env">{{ env }}</Option>
                        </Select>
                    </Form-Item> 
                    <Form-Item label="名字:"  prop="name">
                        <Input type="text"  v-model="site.name" />
                    </Form-Item> 
                    <Form-Item label="链接:"  prop="link">
                            <Input type="text"  v-model="site.link" />
                    </Form-Item> 
                    <Form-Item label="账号:"  prop="account">
                        <Input type="text"  v-model="site.account" />
                    </Form-Item> 
                    <Form-Item label="密码:"  prop="password">
                            <Input type="text"  v-model="site.password" />
                    </Form-Item> 
                    <Form-Item label="描述:"  prop="description">
                        <Input type="textarea"  :rows="10" style="overflow-y:auto"  v-model="site.description" />
                    </Form-Item> 
                </Form> 
            </div>
            <div slot="footer">
                <!-- site是 ref的值 -->
                <Button type="primary" size="large"  @click="submit_add_site('site')">提交</Button>
            </div>
        </Modal>
        <!-- 编辑站点模态框 -->
        <Modal v-model="show_edit_site_modal" width="800" draggable>
            <p slot="header" style="color:#f60;text-align:center">
               {{env_list}} {{ site_edit.env}} <span>编辑站点</span>
            </p>
            <div >
                <Form ref="site_edit" :model="site_edit" :rules="site_rules" label-position="left"  :label-width="100">
                    <Form-Item label="选择环境" prop="env">
                        <Select v-model="site_edit.env">
                            <template v-for="env in env_list" >
                                <Option  :key="env" :value="env" v-if="env === site_edit.env"  selected>{{ env }}</Option>
                                <Option :key="env" :value="env" v-else>{{ env }} </Option>
                            </template>
                         </Select>
                    </Form-Item> 
                    <Form-Item label="名字:"  prop="name">
                        <Input type="text"  v-model="site_edit.name" />
                    </Form-Item> 
                    <Form-Item label="链接:"  prop="link">
                            <Input type="text"  v-model="site_edit.link" />
                    </Form-Item> 
                    <Form-Item label="账号:"  prop="account">
                        <Input type="text"  v-model="site_edit.account" />
                    </Form-Item> 
                    <Form-Item label="密码:"  prop="password">
                            <Input type="text"  v-model="site_edit.password" />
                    </Form-Item> 
                    <Form-Item label="描述:"  prop="description">
                        <Input type="textarea" :rows="10" style="overflow-y:auto" v-model="site_edit.description" />
                    </Form-Item> 
                </Form> 
            </div>
            <div slot="footer">
                <!-- site是 ref的值 -->
                <Button type="primary" size="large"  @click="submit_edit_site('site_edit')">提交</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import axios from 'axios';
import { post } from  '@/api/http'
import { show_simple_page } from '@/common/util'
import {
    site_add,
    site_list,
    site_delete,
    site_update,
    get_env_name_list,
    get_site_by_env_name,
    site_select,
} from '@/api';

export default {
    data() {
        return {
            format: [
                {
                    title: '名字',key: 'name',
                    render: (h,params) => {
                        return h('div',[
                            h('a',{
                                style: {
                                    color: 'blue'
                                },
                                on: {
                                    click: ()=>{                  
                                        this.handleLink(params);
                                    }
                                }
                            },params.row.name)
                        ])
                    }
                },
                {
                    title: '环境',key: 'env'
                },
                {
                    title: '链接',key: 'link'
                },
                {
                    title: '账号',key: 'account'
                },
                {
                    title: '密码',key: 'password'
                },
                {
                    title: '描述',key: 'description',tooltip: true,ellipsis: true,
                },
                {
                    title: '创建时间',key: 'create_time'
                },
                {
                    slot: 'action',width: 150,align: 'center'
                }
            ],
            // 新增站点绑定
            site: {
                name: '',
                link: '',
                account: '',
                password: '',
                description: '账号1: \n密码1：',
                env: 'dev',
            },
            // 环境列表
            env_list: [],
            site_rules: {
                name:[
                    {required: true,message:"请输入站点名称",trigger: 'blur'},
                ],
                link:[
                    {required: true,message:"请输入站点链接地址",trigger: 'blur'},
                ],
            },
            show_add_site_modal: false,
            // 编辑数据
            site_edit: {
                name: '',
                link: '',
                account: '',
                password: '',
                description: '',
                env: '',
            },
            show_edit_site_modal:false,
            // 查询数据
            // env: '',
            selectContent: '',
            // 编辑数据
            show_list: [],
            // 分页
            total: 0,
            pageSize: 15,
        }
    },
    methods: {
        btn_select_site(){
            let selectContent = this.selectContent
            if(selectContent =='' || selectContent==null) {
                // 等同于全表查询
                this.refresh()
                return
            }
            let data = JSON.stringify({"selectContent":selectContent})

            post(site_select,data).then( (response) => {
                show_simple_page(this,response)
            })

        },
        handleLink(params){
            window.open(params.row.link,"_blank");
        },
        submit_edit_site(name){
            let validate = false
            this.$refs[name].validate((valid) => {
                if (valid) validate = true
            })
            if(!validate) return

            let data = {'site':this.site_edit}
            post(site_update,data).then( (response) => {
                let info = JSON.stringify(response.data)
                if(info.indexOf('ok') != -1) {
                    this.$Message.success('更新成功')
                    this.show_edit_site_modal = false
                    this.refresh()
                }else {
                    alert("更新失败:",info)
                }
            })

        },
        btn_edit_site(index){
            this.get_env()
            let site =  JSON.parse(JSON.stringify(this.show_list[index]))
            this.site_edit = site
            setTimeout(() =>{
                this.show_edit_site_modal=true
            },200); 
        },
        // 获取环境列表
        get_env(){
            post(get_env_name_list).then(response =>{
                this.env_list = response.data
            })
        },
        btn_add_site(){
            this.get_env()
            this.show_add_site_modal = true
        },
        async checkUnique(site) {
            let site_name=site.name
            let env = site.env
            let data = {'name':site_name,'env':env}
            let response = await axios({
                method: 'post',
                url: get_site_by_env_name,
                data: data
            })
            let info = response.data
            if(info.msg == true) {
                console.log("非唯一，不可插")
                return false
            }else {
                console.log("可插")
                return true
            } 
        },
        async submit_add_site(name){
            let validate = false
            this.$refs[name].validate((valid) => {
                if (valid) validate = true
            })
            if(!validate) return
            let site = this.site

            // 判断联合主键  axios真麻烦 异步得改同步
            let checkPass  = await this.checkUnique(site)
            if(!checkPass){
                this.$Message.error(site.env+" "+site.name+" 已经存在")
                return   
            }
            let data = {'site':site}
            post(site_add,data).then( (response) => {
                let info = JSON.stringify(response.data)
                if(info.indexOf('ok') != -1) {
                    this.$Message.success('添加'+site.name+'成功')
                    this.show_add_site_modal = false
                    this.refresh()
                }else {
                    alert("添加失败:",info)
                }
            })

        },
        changePage(index) {
            let _start = (index -1) * this.pageSize
            let _end = index * this.pageSize
            this.show_list = this.total_list.slice(_start,_end)
        },
        del_site(index){
            let id = this.show_list[index].id
            let name = this.show_list[index].name
            let result = confirm("确定要删除"+name+"吗?")
            if(result == false) return 

            let data = {"id":id}
            axios({
                url:site_delete,method:'post',data:data,
            }).then( (response) => {
                let info = JSON.stringify(response.data)
                if(info.indexOf('ok') != -1) {
                    this.$Message.success('删除'+name+'成功')
                    this.refresh()
                }else {
                    alert("删除失败:",info)
                }
            })

        },
        refresh() {
            post(site_list).then( (response) => {
                show_simple_page(this,response)
            })
        }
    },
    mounted: function() {
        setTimeout(() =>{
            this.refresh();
        },200); 
    }
}
</script>
<style scoped>

</style>